<template>
  <el-card>
    <div class="card-header">
      角色管理
    </div>
  </el-card>
  <el-card class="content">
    <el-form :inline="true" :model="listForm">
      <el-form-item label="角色名称">
        <el-input v-model="listForm.name" clearable/>
      </el-form-item>
      <el-form-item>
        <perms-button
            perms="privilege:role:list"
            :type="Types.primary"
            :plain="true"
            @action="list"/>
      </el-form-item>
      <el-form-item>
        <perms-button
            perms="privilege:role:add"
            :type="Types.success"
            :plain="true"
            @action="showDialog('add')"/>
      </el-form-item>
    </el-form>
    <el-table
        :data="roles"
        :border="true"
    >
      <template #empty>
        <el-empty/>
      </template>
      <el-table-column prop="name" label="角色名称"/>
      <el-table-column prop="sort_id" label="排序"/>
      <el-table-column prop="status" label="角色状态" width="100" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              :loading="loading"
              inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :active-value="20"
              :inactive-value="10"
              active-text="在用"
              inactive-text="停用"
              @change="handleRoleStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column prop="created_at" label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ timeFormat(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="修改时间" width="180" align="center">
        <template #default="scope">
          {{ timeFormat(scope.row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <perms-link
              perms="privilege:role:update"
              :type="Types.success"
              @action="showDialog('update', scope.row)"/>
          <perms-link
              perms="privilege:role:menu:update"
              :type="Types.primary"
              @action="showDialog('menu', scope.row)"/>
          <perms-link
              perms="privilege:role:api:update"
              :type="Types.warning"
              @action="showDialog('api', scope.row)"/>
          <el-popconfirm
              :title="`确定删除角色[${scope.row.name}]吗?`"
              :icon="InfoFilled"
              icon-color="#F56C6C"
              cancel-button-text="取消"
              confirm-button-text="确认删除"
              cancel-button-type="info"
              confirm-button-type="danger"
              @confirm="deleteRole(scope.row.id)"
              width="300"
          >
            <template #reference>
              <perms-link
                  perms="privilege:role:delete"
                  :type="Types.danger"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page"
        v-model:current-page="listForm.page"
        v-model:page-size="listForm.size"
        :page-sizes="[30, 40, 50, 100]"
        :disabled="loading"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list"
        @current-change="list"
    />
    <el-dialog
        :close-on-click-modal="false"
        v-model="visible"
        :title="dialogTitle"
        :draggable="true"
        append-to-body
        width="600">
      <Menu v-if="visible&&action==='menu'" :role_id="id" :key="new Date().getTime()" @close="closeDialog"/>
      <Api v-else-if="visible&&action==='api'" :role_id="id" :key="new Date().getTime()" @close="closeDialog"/>
      <RoleItem v-else :role-form="roleForm" :action="action" :key="new Date().getTime()" @close="closeDialog"/>
    </el-dialog>
  </el-card>
</template>


<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {RoleAddR, RoleListR, RoleRemoveR, RoleUpdateR, RoleStatusR} from "@/api/role";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {InfoFilled} from "@element-plus/icons-vue";
import * as dayjs from "dayjs";
import PermsButton from '@/components/PermsButton.vue'
import PermsLink from '@/components/PermsLink.vue'
import {ListRequest, RoleMenusListRequest, RoleRequest, RoleStatusRequest} from "@/interface/role"
import Menu from "@/components/role/Menu.vue";
import RoleItem from "@/components/role/RoleItem.vue";
import {Types} from "@/interface/enum";
import Api from "@/components/role/Api.vue";

const initListForm = () => {
  return <ListRequest>{
    page: 1,
    size: 10,
    name: '',
  }
}

const initRoleForm = () => {
  return <RoleRequest>{
    id: 0,
    name: '',//角色名称
    sort_id: 1, //排序
    status: 20,//状态：10.停用，20.在用
    remark: '',//备注
    created_at: 0,
    updated_at: 0,
  }
}

const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const dialogTitle = ref<string>('')
const action = ref<string>('')

//表单
const formRef = ref<FormInstance>()
const listForm = ref<ListRequest>(initListForm())
const roleForm = ref<RoleRequest>(initRoleForm())

//分配菜单
const id = ref<number>(0)

//角色列表
const roles = ref<RoleRequest[]>([])
const total = ref<number>(0)

//表单校验
const rules = reactive<FormRules>({
  name: [
    {required: true, message: '必填', type: "string", trigger: ['blur', 'change']}
  ],
  sort_id: [
    {required: true, message: '必填', type: "number", trigger: ['blur', 'change']}
  ],
  status: [
    {required: true, message: '必填', type: "enum", enum: [10, 20], trigger: ['blur', 'change']}
  ]
})

const closeDialog = () => {
  visible.value = false
  list()
}

//查询角色列表
const list = () => {
  loading.value = true
  RoleListR(listForm.value).then(res => res.data).then(res => {
    loading.value = false
    switch (res.code) {
      case 200:
        roles.value = res.data.list
        total.value = res.data.total
        break
      default:
        //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    ElMessage.error(err.toString())
  })
}

const showDialog = (act: string, role?: RoleRequest) => {
  switch (act) {
    case 'add':
      action.value = act
      roleForm.value = initRoleForm()
      visible.value = true
      dialogTitle.value = '添加角色'
      break
    case 'update':
      action.value = act
      roleForm.value = JSON.parse(JSON.stringify(role as RoleRequest))
      visible.value = true
      dialogTitle.value = '修改角色'
      break
    case 'menu':
      action.value = act
      dialogTitle.value = '分配菜单 - '+role!.name
      id.value = (role as RoleRequest).id
      console.log('分配菜单:', id.value)
      visible.value = true
      break
    case 'api':
      action.value = act
      dialogTitle.value = '分配 API - '+role!.name
      id.value = (role as RoleRequest).id
      visible.value = true
      break
    default:
      ElMessage.error('未知操作')
  }
}

const handleSubmit = () => {
  switch (action.value) {
    case 'add':
      addRole()
      break
    case 'update':
      editRole()
      break
    default:

  }
}

//新增角色
const addRole = () => {
  RoleAddR(roleForm.value).then(res => res.data).then(res => {
    switch (res.code) {
      case 200:
        ElMessage.success(res.msg)
        list()
        visible.value = false
        break
      default:
        // ElMessage.error(res.msg)
    }
  })
}

//修改
const editRole = () => {
  RoleUpdateR(roleForm.value).then(res => res.data).then(res => {
    switch (res.code) {
      case 200:
        ElMessage.success(res.msg)
        list()
        visible.value = false
        break
      default:
        // ElMessage.error(res.msg)
    }
  })
}

//更改角色状态
const handleRoleStatus = (role: RoleRequest) => {
  if (role.id as number <= 0) {
    ElMessage.warning('角色不存在')
    return false
  }

  loading.value = true
  let req = <RoleStatusRequest>({id: role.id, status: role.status})
  RoleStatusR(req).then(res => res.data).then(res => {
    loading.value = false
    switch (res.code) {
      case 200:
        ElMessage.success(res.msg)
        list()
        break
      default:
        list()
        //ElMessage.error(res.msg)
    }
    return false
  }).catch(err => {
    loading.value = false
    ElMessage.error(err.toString())
    list()
  })
}

//删除角色
const deleteRole = (id: number) => {
  if (id <= 0) {
    ElMessage.error('角色不存在')
    return
  }

  let req = <RoleMenusListRequest>({id:id})
  RoleRemoveR(req).then(res => res.data).then(res => {
    switch (res.code) {
      case 200:
        ElMessage.success(res.msg)
        list()
        break
      default:
        //ElMessage.error(res.msg)
    }
  })
}

onMounted(() => {
  list()
})

//时间格式
const timeFormat = (timestamp: number) => {
  return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
</script>


<style scoped lang="less">
.el-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page {
  margin-top: 10px;
}

.links {
  padding-right: 10px;
}
</style>